<?php
class ConfigController extends Zend_Controller_Action
{
    public function indexAction()
    {    	    	 
    	$view = Zend::registry('view');
        echo $view->render('configAccueilView.php');     
    }

    public function gestionCamAction()
    {
    	$db = Zend::registry('db');    	
    	$queryThreads = "SELECT * FROM threads";
    	$selectThreads = $db->query($queryThreads);
    	$myThreads = $selectThreads->fetchAll();
    	 
    	$view = Zend::registry('view');
    	$view->threads = $myThreads;
        echo $view->render('configListCamView.php');     
    }

    public function afficheFormAction()
    {
/*        $get = Zend::registry('fGet');
        $db = Zend::registry('db');
        $myLogin = $get->getRaw('login');       

        $sql = "SELECT admin FROM users WHERE login = '" . $myLogin . "'";
        $myAdmin = $db->fetchOne($sql);
        if ( $myAdmin == 'O' ) $myAdmin = "checked";
            else $myAdmin = "";
*/
        $view = Zend::registry('view');
        echo $view->render('configNewCamView.php');
    }

    public function initMotionAction()
    {
        $myModelFilePath = C_MOTION_MODEL_FILE;
        $myConfFilePath = C_CONF_PATH . "motion.conf";
        exec('cp ' . $myModelFilePath . ' ' . $myConfFilePath);
        
        $this->_redirect('/');
    }
    
    public function viewFileAction()
    {
     	$view = Zend::registry('view');
        
        $get = Zend::registry('fGet');
        $myThreadId = $get->getRaw('threadId');
        $myThreadName = $get->getRaw('threadName');        
        $myConfFile = C_CONF_PATH . $myThreadName . ".conf";
        $myMaskFile = C_CONF_PATH . $myThreadName . ".pgm";
        $newFile = false;

        if ( !file_exists($myConfFile) )
        {
            $myConfFile = C_THREAD_MODEL_FILE;
            $newFile = true;
        }
           
        if ( $file = fopen($myConfFile, "r") ){
            $myFileContent = "";
            while (!feof ($file)) {
                $myFileContent .= fgets($file, 4096);
                if ( $newFile ){
                    $myFileContent = ereg_replace('{recordDirName}', C_MOTION_FULLDIR.$myThreadName, $myFileContent);
                    $myFileContent = ereg_replace('{cameraName}', strtoupper($myThreadName), $myFileContent);
                    $myFileContent = ereg_replace('{cameraId}', $myThreadId, $myFileContent);
                    $myFileContent = ereg_replace('{maskFile}', $myMaskFile, $myFileContent);
                }
            }
            fclose ( $file );
            $myConfFile = C_CONF_PATH . $myThreadName . ".conf";      
        }                
        
        $view->threadName = $myThreadName;
        $view->threadId = $myThreadId;
        $view->fileContent = stripslashes($myFileContent);
        $view->filePath = $myConfFile;    
        echo $view->render('configFileView.php'); 
    }

    public function recordFileAction() 
    {
        $post = Zend::registry('fPost'); 
                   
        $myFileContent = $post->getRaw('fileContent');    
        $myThreadId = $post->getRaw('threadId');
        $myThreadName = $post->getRaw('threadName');
        $myFilePath = C_CONF_PATH . $myThreadName . ".conf";

        if ( !file_exists($myFilePath) )
        {                          
            $db = Zend::registry('db');  
            $sql = "INSERT INTO threads(id,name) VALUES ('" . $myThreadId . "', '" . $myThreadName . "')";
            $db->query($sql);
        }

        if ( $file = fopen( $myFilePath, "w" ) ) {
            fwrite($file, stripslashes($myFileContent));
            fclose($file);
        }
        $this->_redirect('/config/gestionCam');
    }

    public function viewCrontabAction()
    {
        // Ouverture du fichier /etc/crontab et affichage        
     	$view = Zend::registry('view');                

        // Recuperation du chemin au fichier crontab
        $myFile = "/etc/crontab";

        if ( $file = fopen($myFile, "r") ){
            $myFileContent = "";
            while (!feof ($file)) {
                $myFileContent .= fgets($file, 4096);
            }
            fclose ( $file );            
        }                
        
        $view->fileContent = stripslashes($myFileContent);
        $view->filePath = $myFile;    
        echo $view->render('configCrontabView.php'); 
    }

    public function recordCrontabAction() 
    {
        $post = Zend::registry('fPost'); 
                   
        // Recuperation du chemin au fichier crontab
        $myFile = "/etc/crontab";
        $myFileContent = $post->getRaw('fileContent');    

        if ( $file = fopen( $myFile, "w" ) ) {
            fwrite($file, stripslashes($myFileContent));
            fclose($file);
        }
        $this->_redirect('/config');
    }

    public function deleteFileAction()
    {
        $get = Zend::registry('fGet');
        $db = Zend::registry('db');
        $myThreadName = $get->getRaw('threadName');
        $myThreadId = $get->getRaw('threadId');
        $myConfFile = C_CONF_PATH . $myThreadName . ".conf";
        $myMaskFile = C_CONF_PATH . $myThreadName . ".pgm";

        $myThreadDir = C_MOTION_DIR . $myThreadName . '/';

        if ( file_exists($myConfFile) ) {
            // Suppression des elements de la base de données
            $sql = "DELETE FROM security WHERE camera = '".$myThreadId."'";
            $db->query($sql);
            $sql = "DELETE FROM threads WHERE id = '" . $myThreadId . "'";
            $db->query($sql);
            
            // Suppression des enregistrements et du dossier de la camera
            if (is_dir($myThreadDir)) {
                if ( $myDir = opendir($myThreadDir)) {
                    while ( ($myFile = readdir($myDir)) !== false) {
                        if ( !is_dir($myThreadDir.$myFile) ){
                            unlink($myThreadDir.$myFile);            
                        }
                    }
                    closedir($myDir);
                }
                rmdir($myThreadDir);
            }

            // Suppression du fichier de mask si il existe
            if ( file_exists($myMaskFile) ){
                unlink ($myMaskFile);                
            }
            
            // Suppression du fichier de configuration de la camera
            unlink($myConfFile);                            
        }
        $this->_redirect('/config/gestionCam');                               
    }

    public function getMaskAction()
    {
    	$db = Zend::registry('db');
        $get = Zend::registry('fGet');
        $myThreadId = $get->getRaw('threadId');                                                             
                
        if ( $myResponse = @file(C_CONTROL_MOTION . '/' . $myThreadId . '/action/snapshot') ){               
            $sql = "SELECT * FROM security, threads WHERE camera = id AND file_type = '2' AND camera = '" . $myThreadId . "' ORDER BY time_stamp DESC";
            $myThread = $db->fetchRow($sql);
            $mySnapshot = C_MOTION_DIR . $myThread['name'] . '/' . basename($myThread['filename']); 
            $myThreadName = $myThread['name'];
        } else $mySnapshot = "";          
        
        $view = Zend::registry('view');
        $view->threadId = $myThreadId;
        $view->threadName = $myThreadName;
        $view->snapshot = $mySnapshot;
        echo $view->render('configMaskCamView.php');
    }

    public function sendMaskAction()
    {
        $db = Zend::registry('db');
        $get = Zend::registry('fPost');        
        $myThreadId = $get->getRaw('threadId');
        
        $sql = "SELECT name FROM threads WHERE id = '" . $myThreadId . "'";

        $myThreadName = $db->fetchOne($sql);
        
        $uploadfile = C_CONF_PATH . $_FILES['userfile']['name'];
        $endFile = C_CONF_PATH . $myThreadName . '.pgm';
        
        if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) )
        {
            exec('convert ' . $uploadfile . ' ' . $endFile);
            unlink($uploadfile);            
        }   
                     
        $this->_redirect('/');                       
    }

    public function noRouteAction()
    {
        $this->_redirect('/');
    }
}
?>
